# coding=utf-8
import hashlib
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.utils import six
from django.utils.crypto import get_random_string, salted_hmac
from django.db import models
import time


MEMBER_ROLES = (
    ('owner', '拥有者'),
    ('admin', '管理员'),
    ('general', '成员'),
    ('guest', '访客'),
)

INVITATION_STATUES = (
    ('inactive', '邀请中'),
    ('accepted', '已接受'),
    ('canceled', '已取消'),
    ('rejected', '已拒绝'),
)


class Team(models.Model):
    name = models.CharField('名称', max_length=32)
    date_join = models.DateTimeField('创建时间', auto_now_add=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='u+')
    members = models.ManyToManyField(settings.AUTH_USER_MODEL, through='TeamMemberShip')

    class Meta:
        verbose_name = '团队'
        verbose_name_plural = '团队'

    def invite_member(self, email):
        token = get_random_string(32)
        invitation = Invitation(team=self, email=email, token=token)
        invitation.save()
        return token

    def member_exists_by_email(self, email):
        return self.members.exists(email=email)

    def add_member(self, member, role='general'):
        ship = TeamMemberShip(team=self, member=member, role=role)
        ship.save()

    def get_absolute_url(self):
        from django.core.urlresolvers import reverse

        return reverse('team.views.show', args=[six.string_types(self.id)])

    @staticmethod
    def join(token):
        try:
            invitation = Invitation.objects.get(token=token)
        except ObjectDoesNotExist:
            return

        invitation.is_accept = True
        invitation.save()
        return invitation.team


class TeamMemberShip(models.Model):
    team = models.ForeignKey(Team)
    member = models.ForeignKey(settings.AUTH_USER_MODEL)
    role = models.CharField(choices=MEMBER_ROLES, max_length=32, default='general')

    @property
    def can_admin(self):
        return self.role == 'owner' or self.role == 'admin'


class Invitation(models.Model):
    email = models.EmailField('电子邮箱', max_length=64)
    token = models.CharField('令牌', max_length=64, unique=True)
    team = models.ForeignKey(Team, verbose_name='团队')
    status = models.CharField('状态', max_length=16, choices=INVITATION_STATUES, default='inactive')
    date_join = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        index_together = [
            ["team", "status"]
        ]
        ordering = ('id',)

    def generate_token(self):
        value = six.text_type(self.team.pk) + six.text_type(time.time()) + six.text_type(get_random_string(6))
        self.token = hashlib.md5(value).hexdigest()
        return self

    @property
    def name(self):
        return self.email.split('@')[0]
